package com.sz.szaiagent.advisor;

import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义 Re2 Advisor
 * 该类用于提高大型语言模型的推理能力，通过重复读取用户输入的问题来增强模型的响应。
 */
public class ReReadingAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    /**
     * 在请求处理前对用户输入进行处理
     * @param advisedRequest 用户请求
     * @return 处理后的请求
     */
    private AdvisedRequest before(AdvisedRequest advisedRequest) {
        Map<String, Object> advisedUserParams = new HashMap<>(advisedRequest.userParams());
        advisedUserParams.put("re2_input_query", advisedRequest.userText());

        return AdvisedRequest.from(advisedRequest)
                .userText("""
                        {re2_input_query}
                        Read the question again: {re2_input_query}
                        """)
                .userParams(advisedUserParams)
                .build();
    }

    /**
     * 在调用链中处理请求
     * @param advisedRequest 用户请求
     * @param chain 调用链
     * @return 处理后的响应
     */
    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        return chain.nextAroundCall(this.before(advisedRequest));
    }

    /**
     * 在流处理中处理请求
     * @param advisedRequest 用户请求
     * @param chain 流处理链
     * @return 处理后的响应流
     */
    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        return chain.nextAroundStream(this.before(advisedRequest));
    }

    /**
     * 获取顾问的优先级
     * @return 优先级值
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 获取顾问的名称
     * @return 顾问名称
     */
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }
}

